  
ALTER PROCEDURE [dbo].[Zonas_GetAllPaginated]  
 @IdZona int = NULL,          
 @IdDivision int = NULL,          
 @Descripcion varchar(50) = NULL,          
 @PageNum int = NULL,              
 @PageSize int = NULL,            
 @PageCount int output              
AS            
SELECT           
 IdZona, IdDivision, Descripcion, IdVendedorGteZonal, Vendedor
FROM  ( SELECT Z.IdZona,Z.IdDivision,Z.Descripcion,Z.IdVendedorGteZonal,V.Apellido + ', ' + V.Nombre as Vendedor, ROW_NUMBER()            
  OVER (ORDER BY Z.Descripcion) AS RowNumber             
  FROM Zonas Z LEFT JOIN Vendedores V on Z.IdVendedorGteZonal = V.IdVendedor
  WHERE (IdZona  = @IdZona  or @IdZona is null) AND             
  (IdDivision = @IdDivision or @IdDivision is null) AND             
        (Z.Descripcion like '%' +  @Descripcion + '%' or @Descripcion is null)) AS Page            
WHERE RowNumber             
  BETWEEN (@PageSize * @PageNum + 1) AND (@PageSize * (@PageNum + 1))            
  or @PageNum is null      
              
select @PageCount=COUNT(*)            
  FROM Zonas Z    
  WHERE 
	(IdZona  = @IdZona  or @IdZona is null) AND             
	(IdDivision = @IdDivision or @IdDivision is null) AND             
    (Z.Descripcion like '%' +  @Descripcion + '%' or @Descripcion is null)  
          


GO

  
ALTER PROCEDURE [dbo].[Zonas_i]  
 @Descripcion varchar(50),  
 @IdDivision int,  
 @IdVendedorGteZonal int,
 @IdZona int output   
AS  
INSERT INTO Zonas  
           ([Descripcion]  
           ,[IdDivision] 
           ,[IdVendedorGteZonal] 
           )  
     VALUES  
           (@Descripcion  
           ,@IdDivision
           ,@IdVendedorGteZonal)  
SELECT @IdZona =  SCOPE_IDENTITY()  
  
GO

ALTER PROCEDURE [dbo].[Zonas_u]  
@IdZona int,  
@IdDivision int,  
@Descripcion varchar(50),
@IdVendedorGteZonal int
AS  
UPDATE Zonas  
   SET [Descripcion] = @Descripcion  
    ,[IdDivision] = @IdDivision
    ,[IdVendedorGteZonal] = @IdVendedorGteZonal
 WHERE IdZona = @IdZona  
  
GO

